package org.android.brasil.projetos.oktoberfest2011.view;

import java.util.List;

import org.android.brasil.projetos.oktoberfest2011.R;
import org.android.brasil.projetos.oktoberfest2011.negocio.model.Apresentacao;
import org.android.brasil.projetos.oktoberfest2011.negocio.model.Horario;
import org.android.brasil.projetos.oktoberfest2011.persistencia.ApresentacaoDAO;
import org.android.brasil.projetos.oktoberfest2011.persistencia.HorarioDAO;
import org.android.brasil.projetos.oktoberfest2011.utils.AnalyticsUtils;
import org.android.brasil.projetos.oktoberfest2011.utils.Constantes;
import org.android.brasil.projetos.oktoberfest2011.utils.ControleDeBackground;
import org.android.brasil.projetos.oktoberfest2011.utils.DataUtil;
import org.android.brasil.projetos.oktoberfest2011.view.controller.HomeController;

import android.app.Dialog;
import android.app.ListActivity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class AgendaView extends ListActivity implements OnGestureListener {

	private ListView lvProgramacao;
	public static int dia = 0;
	//public static boolean home;
	private TextView tvDia;
	private TextView tvTitulo;
	private String setor;
	private RelativeLayout rl;
	//private boolean clicouNaCasa;
	private List<Apresentacao> aprs;

	// gesture variables
	// more details here
	// http://www.ceveni.com/2009/08/android-gestures-detection-sample-code.html
	// and here
	// http://stackoverflow.com/questions/3921138/gesture-in-listview-android
	private static final int SWIPE_MIN_DISTANCE = 60;
	private static final int SWIPE_MAX_OFF_PATH = 150;
	private static final int SWIPE_THRESHOLD_VELOCITY = 100;

	private GestureDetector gestureScanner;
	private AnalyticsUtils mGa;

	private OnClickListener casaListener = new OnClickListener() {

		public void onClick(View v) {

			AgendaView.dia = 0;
			//home = true;
			//clicouNaCasa = true;
			Intent i = new Intent(getApplicationContext(),HomeController.class);
			i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(i);
			/*setResult(RESULT_OK);
			finish();*/
			mGa.buttonTrackEvent("Casa");
		}
	};

	private OnClickListener buscarListener = new OnClickListener() {

		public void onClick(View v) {
			Intent i = new Intent(getApplicationContext(),BuscarView.class);
			startActivity(i);
			mGa.buttonTrackEvent("Busca");
		}
	};

	@Override
	protected void onResume() {
		super.onResume();
		populateFields();
	}

	@Override
	protected void onPause() {
		super.onPause();
		/*if (!clicouNaCasa) {
			home = false;
		}*/
	}

	@Override
	protected void onRestart() {
		super.onRestart();
		populateFields();
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		this.mGa = AnalyticsUtils.getInstance(this);
		
		setContentView(R.layout.agenda_view);
		registerForContextMenu(getListView());

		final GestureDetector gestureDetector = new GestureDetector(
				new MyGestureDetector());
		View.OnTouchListener gestureListener = new View.OnTouchListener() {
			public boolean onTouch(View v, MotionEvent event) {
				return gestureDetector.onTouchEvent(event);
			}
		};

		ListView lv = getListView();
		lv.setOnTouchListener(gestureListener);
		bindScreenFields();
		setor = getIntent().getStringExtra("SETOR");
		int d = getIntent().getIntExtra("DIA", 0);
		if (dia < Constantes.DIA_INICIO_OKTOBERFEST) {
			dia = d;
		}

		if (dia == 0) {
			dia = Constantes.DIA_INICIO_OKTOBERFEST;
		}
		populateFields();

		// gesture
		gestureScanner = new GestureDetector(this);

		
		
		final Dialog dialog = new Dialog(this);

		dialog.setContentView(R.layout.compartilhar_dialog);
		dialog.setTitle(R.string.compartilhar);
		
		final CheckBox check = (CheckBox) dialog.findViewById(R.idDialog.check);
		SharedPreferences settings = getSharedPreferences(
				Constantes.COMPARTILHAR, 0);
		boolean checked = settings.getBoolean(Constantes.COMPARTILHAR, false);

		
		Button ok = (Button) dialog.findViewById(R.idDialog.ok);
		ok.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {

				SharedPreferences settings = getSharedPreferences(
						Constantes.COMPARTILHAR, 0);
				SharedPreferences.Editor editor = settings.edit();
				editor.putBoolean(Constantes.COMPARTILHAR, check.isChecked());

				editor.commit();
				dialog.dismiss();
			}
		});

		if(!checked){
			dialog.show();
		}
		
		this.mGa.trackScreen(getString(R.string.agenda)+ " - view");
	}

	private void bindScreenFields() {

		lvProgramacao = getListView();

		ImageView diaAnterior = (ImageView) findViewById(R.idAgenda.dia_anterior);
		diaAnterior.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				onRightSwipe();
			}
		});
		tvDia = (TextView) findViewById(R.idAgenda.dia);

		tvTitulo = (TextView) findViewById(R.id.titulo);

		rl = (RelativeLayout) findViewById(R.idAgenda.relativeLayout01);

		ControleDeBackground.SetBarraSuperiorBackGround(
				getApplicationContext(), rl);

		ImageView proximoDia = (ImageView) findViewById(R.idAgenda.proximo_dia);

		proximoDia.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				onLeftSwipe();

			}
		});

		ImageView casa = (ImageView) findViewById(R.id.casa);
		casa.setOnClickListener(casaListener);

		ImageView busca = (ImageView) findViewById(R.id.buscar);
		busca.setOnClickListener(buscarListener);

	}

	private void populateFields() {

		String data = "";
		if (DataUtil.ehHoje(dia)) {
			data = getResources().getString(R.string.hoje) + " \n";
		}
		data = data + (dia + Constantes.MES_E_ANO);

		data = data
				+ " - "
				+ DataUtil.retornarDiaSemana(Constantes.ANO_DA_OKTOBERFEST,
						Constantes.CALENDAR_MES_DA_OKTOBERFEST, dia);
		HorarioDAO.open(getApplicationContext());
		Horario hor = HorarioDAO.consultarPorDia(dia);
		HorarioDAO.close();

		data = data + " - " + DataUtil.formatarHora(hor.getAbertura())
				+ getResources().getString(R.string._as_)
				+ DataUtil.formatarHora(hor.getFechamento());
		tvDia.setText(data);
		tvTitulo.setText(getResources().getString(R.string.programacao) + " - "
				+ setor);

		ApresentacaoDAO.open(getApplicationContext());
		aprs = ApresentacaoDAO.consultarShowsPorSetorEDia(setor, dia);
		ApresentacaoDAO.close();

		lvProgramacao.setAdapter(new AgendaAdapter(getApplicationContext(),
				aprs));

	}

	// gesture part

	public boolean onTouchEvent(MotionEvent me) {
		return gestureScanner.onTouchEvent(me);
	}

	public boolean onDown(MotionEvent e) {
		return true;
	}

	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
			float velocityY) {
		try {
			if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH)
				return false;
			// right to left swipe
			if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE
					&& Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
				onLeftSwipe();
			} else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE
					&& Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
				onRightSwipe();
			}
		} catch (Exception e) {
			// nothing
		}

		return true;
	}

	public void onLongPress(MotionEvent e) {
		// do nothing in the long press
	}

	public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
			float distanceY) {
		// do nothing in the scroll event
		return true;
	}

	public void onShowPress(MotionEvent e) {
		// do nothing here also...
	}

	public boolean onSingleTapUp(MotionEvent e) {
		// do nothing in the single tap
		return true;
	}

	private void onLeftSwipe() {
		if (dia < Constantes.DIA_FIM_OKTOBERFEST) {
			dia = dia + 1;
			populateFields();
		}
	}

	private void onRightSwipe() {
		if (dia > Constantes.DIA_INICIO_OKTOBERFEST) {
			dia = dia - 1;
			populateFields();

		}
	}

	// cuida do gesture para a list view, para o restante do activity,
	// é o proprio implements OnGestureListener que cuida
	class MyGestureDetector extends SimpleOnGestureListener {

		// Detect a single-click and call my own handler.
		@Override
		public boolean onSingleTapUp(MotionEvent e) {
			return false;
		}

		@Override
		public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
				float velocityY) {
			if (e1 != null) {
				if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH)
					return false;
				if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE
						&& Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
					onLeftSwipe();
				} else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE
						&& Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
					onRightSwipe();
				}
			}
			return false;
		}

	}

	protected void onDestroy() {
		super.onDestroy();
	}
}
